package com.toune.movie.mvp.fragment;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

import com.google.zxing.Result;
import com.siberiadante.customdialoglib.BottomPopupWindow;
import com.siberiadante.customdialoglib.EnsureDialog;
import com.toune.movie.R;
import com.toune.movie.base.BaseFragment;
import com.toune.movie.base.myUtil.ReDecodeThread;
import com.toune.movie.base.myview.LargeImageDialog;
import com.toune.movie.mvp.activity.PayActivity;
import com.toune.movie.mvp.contract.GamesContract;
import com.toune.movie.mvp.presenter.GamesPresenter;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.RxImageTool;
import com.vondear.rxtool.view.RxToast;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/5/9.
 */

public class GamesFragment extends BaseFragment<GamesPresenter> implements GamesContract.View {

    private static GamesFragment fragment;
    @BindView(R.id.we_money_iv)
    ImageView weMoneyIv;
    @BindView(R.id.ali_money_iv)
    ImageView aliMoneyIv;
    @BindView(R.id.work_iv)
    ImageView workIv;
    Unbinder unbinder;
    @BindView(R.id.qq_iv)
    ImageView qqIv;
    @BindView(R.id.wechat_iv)
    ImageView wechatIv;
    Unbinder unbinder1;
    private int payType = 1;

    public static GamesFragment newInstance() {
        if (fragment == null) {
            fragment = new GamesFragment();
        }
        return fragment;
    }

    @Override // 实例化presenter
    public GamesPresenter initPresenter() {
        return new GamesPresenter();
    }

    @Override
    public void loadMore() {

    }

    @Override
    public void refreData() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void init(Bundle savedInstanceState) {
        //临时点击事件
        weMoneyIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        weMoneyIv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 长按识别二维码
                payType = 2;
                getQrCode(RxImageTool.getBitmap(R.mipmap.we_money), "weixinpay.png");
                return true;
            }
        });
        aliMoneyIv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                payType = 1;
                getQrCode(RxImageTool.getBitmap(R.mipmap.ali_money), "alipay.png");
                return true;
            }
        });
        workIv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                payType = 2;
                getQrCode(RxImageTool.getBitmap(R.mipmap.work), "workpay.png");
                return true;
            }
        });

        workIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxImageTool.save(RxImageTool.getBitmap(R.mipmap.work), galleryPath + "workpay.png", Bitmap.CompressFormat.PNG);
                LargeImageDialog largeImageDialog = new LargeImageDialog(getContext(), R.layout.dialog_large_image, RxFileTool.getSDCardPath() + "DCIM/" + "workpay.png");
                largeImageDialog.show();
            }
        });
    }

    private final int QR = 101;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String url = bundle.getString("url");
            String fileName = bundle.getString("fileName");
            Bitmap bitmap = bundle.getParcelable("bitmap");
//            if (url == null) {
//                showAlert(bitmap, fileName);
//            } else {
            showSelectAlert(bitmap, url, fileName);
//            }
        }
    };

    private void getQrCode(final Bitmap obmp, final String fileName) {

        Result result = null;
        try {
            ReDecodeThread.encode(obmp, new ReDecodeThread.ReDecodeThreadResult() {
                @Override
                public void onReDecodeResult(String url) {
                    Message message = new Message();
                    message.what = QR;
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putString("fileName", fileName);
                    bundle.putParcelable("bitmap", obmp);
                    message.setData(bundle);
                    handler.sendMessage(message);

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showAlert(final Bitmap bitmap, final String fileName) {
        EnsureDialog builder = new EnsureDialog(getActivity()).builder();
        builder.setTitle("保存图片")
                .setCancelable(false)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RxImageTool.save(bitmap, galleryPath + fileName, Bitmap.CompressFormat.PNG);
                        tellSystemPhoto(bitmap, galleryPath + fileName);
                        RxToast.success("已经保存到本地");
                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        builder.show();
    }

    String galleryPath = Environment.getExternalStorageDirectory()
            + File.separator + Environment.DIRECTORY_DCIM
            + File.separator + "Camera" + File.separator;

    private void showSelectAlert(final Bitmap bitmap, final String url, final String fileName) {
        BottomPopupWindow builder = new BottomPopupWindow(getActivity()).builder();
        builder.setTitle("请选择");
        String str[] = {"保存图片", "扫二维码"};
        builder.addSheetItem(str[0], BottomPopupWindow.SheetItemColor.Blue, new BottomPopupWindow.OnSheetItemClickListener() {
            @Override
            public void onClick(int i) {
                RxImageTool.save(bitmap, galleryPath + fileName, Bitmap.CompressFormat.PNG);
                tellSystemPhoto(bitmap, galleryPath + fileName);
                RxToast.success("图片已经保存到本地");
            }
        })
                .addSheetItem(str[1], BottomPopupWindow.SheetItemColor.Blue, new BottomPopupWindow.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int i) {
                        if (payType == 1) {
                            Intent intent = new Intent(getActivity(), PayActivity.class);
                            intent.putExtra("url", url);
                            intent.putExtra("payType", payType);
                            startActivity(intent);
                        } else {
                            RxImageTool.save(bitmap, galleryPath + fileName, Bitmap.CompressFormat.PNG);
                            tellSystemPhoto(bitmap, galleryPath + fileName);
                            openWeixinToQE_Code(getContext());
                            RxToast.success("图片已经保存到本地");
                        }
//                        Uri uri = Uri.parse(url);
//                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                        startActivity(intent);
                    }
                }).setCanceled(true).show();
    }


    private void tellSystemPhoto(Bitmap bmp, String fileName) {
        //通知相册更新
        MediaStore.Images.Media.insertImage(getContext().getContentResolver(),
                bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(RxFileTool.getFileByPath(fileName));
        intent.setData(uri);
        getContext().sendBroadcast(intent);
    }

    /**
     * 打开微信并跳入到二维码扫描页面
     *
     * @param context
     */
    public void openWeixinToQE_Code(Context context) {
        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
            intent.putExtra("LauncherUI.From.Scaner.Shortcut", true);
            context.startActivity(intent);

        } catch (Exception e) {
            RxToast.info("打开微信失败");
        }
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_games;
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void useNightMode(boolean isNight) {

    }

    @OnClick({R.id.qq_iv, R.id.wechat_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.qq_iv:
                if (checkApkExist(getContext(), "com.tencent.mobileqq")) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + 783466955 + "&version=1")));
                } else {
                    RxToast.info("本机未安装QQ应用");
                }
                break;
            case R.id.wechat_iv:
                shareToFriend(getContext(), getChattingID(getContext(), "", ""));
                break;
        }
    }

    public boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public final static String WEIXIN_CHATTING_MIMETYPE = "vnd.android.cursor.item/vnd.com.tencent.mm.chatting.profile";//微信聊天

    /**
     * 进去聊天界面
     *
     * @param context
     * @param id      手机通讯录中版本的微信的自动增长列（下面有一个方法或告诉大家如何获取）
     */
    public static void shareToFriend(Context context, int id) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.withAppendedPath(
                ContactsContract.Data.CONTENT_URI, String.valueOf(id)),
                WEIXIN_CHATTING_MIMETYPE);
        context.startActivity(intent);
    }

    /**
     * 根据电话号码查询微信id
     **/
    public static int getChattingID(Context context, String querymobile, String mimeType) {
        if (context == null || querymobile == null || querymobile.equals("")) {
            return 0;
        }
        ContentResolver resolver = context.getContentResolver();
        Uri uri = Uri.parse("content://com.android.contacts/data");
        StringBuilder sb = new StringBuilder();
        sb.append(ContactsContract.Data.MIMETYPE).append(" = ").append("'");
        sb.append(mimeType).append("'");
        sb.append(" AND ").append("replace(data1,' ','')").append(" = ").append("'").append("18236912292").append("'");
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Data._ID}, sb.toString(), null, null);
        while (cursor.moveToNext()) {
            int wexin_id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Data._ID));
            return wexin_id;
        }
        cursor.close();
        return 0;
    }
}
